import { createSlice } from '@reduxjs/toolkit'
import {  setToken as _setToken, getToken, removeToken } from '@/utils'
import {loginApi,getProfileApi} from '@/apis/user'

const userStore = createSlice({
  name: 'user',
  // 数据状态
  initialState: {
    token: getToken || '',
    userInfo: {}
  },
  // 同步修改方法
  reducers: {
    setToken (state, action) {
      state.setToken = action.payload
      // 本地存储
      _setToken(action.payload)
    },
    setUserInfo (state, action) {
      state.userInfo = action.payload
    },
    clearUserInfo(state){
      state.token=''
      state.userInfo={}
      removeToken()
    }
  }
})

// 解构出actionCreater
const { setToken, setUserInfo,clearUserInfo } = userStore.actions

// 获取reducer函数
const userReducer = userStore.reducer

// 异步方法封装
const fetchLogin = (loginForm) => {
  return async (dispatch) => {
    //1.发送异步请求
    const res = await loginApi(loginForm)
    console.log('res', res);
    //2.提交同步action，存储token
    dispatch(setToken(res.data.token))
  }
}
const fetchUserInfo = () => {
  return async (dispatch) => {
    //1.发送异步请求
    const res = await getProfileApi()
    console.log('res', res);
    //2.提交同步action，存储
    dispatch(setUserInfo(res.data))
  }
}

export { fetchLogin, fetchUserInfo,clearUserInfo }

export default userReducer